package com.jmlee.service.impl;

import com.jmlee.bo.SecKillOrderBO;
import com.jmlee.cache.SecKillCache;
import com.jmlee.mapper.SecKillItemsMapper;
import com.jmlee.mapper.SecKillOrderMapper;
import com.jmlee.pojo.CommonResult;
import com.jmlee.pojo.SecKillItems;
import com.jmlee.pojo.SecKillOrders;
import com.jmlee.service.SecKillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description
 * @Author jmLee
 * @Date 2021/3/17 23:18
 * @Version 1.0
 */
@Service
public class SecKillServiceImpl implements SecKillService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecKillServiceImpl.class);

    @Autowired
    private SecKillCache secKillCache;

    @Autowired
    private SecKillItemsMapper secKillItemsMapper;

    @Autowired
    private SecKillOrderMapper secKillOrderMapper;


    /**
     * 执行秒杀
     * @param secKillOrderBO
     */
    @Override
    @Transactional
    public CommonResult doSecKill(SecKillOrderBO secKillOrderBO) {


        // 查询秒杀商品信息(系统启动之后，信息已缓存到Redis中了)
        SecKillItems itemInfo = secKillCache.getItem(secKillOrderBO.getItemId());



        // 扣减数据库中的库存
        Long updateNum = secKillItemsMapper.deduceStock(secKillOrderBO.getItemId());
        if (updateNum <= 0) {
            throw new RuntimeException("商品已售完");
        }


        // 创建秒杀订单（采用消息队列进行异步下单，等待下单成功后再通知客户）
        SecKillOrders secKillOrders = new SecKillOrders();
        secKillOrders.setUserId(secKillOrderBO.getUserId());
        secKillOrderMapper.insertOrder(secKillOrders);


        // 将用户的订单信息缓存到Redis中，主要是为了防止用户重复下单（每人限定一单）
        secKillCache.setOrderInfo(secKillOrderBO.getUserId(),itemInfo.getId(), secKillOrders,itemInfo.getExpiredTime());


        return CommonResult.success("下单成功");
    }


    @Override
    public List<SecKillItems> getItemInfo() {

        return secKillCache.getItemInfos();
    }
}
